package cn.lil.filter;

import cn.lil.model.User;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter(filterName = "EncodeFilter")
public class EncodeFilter implements Filter {
    public static String defaultUrl;
    // 不拦截的资源类型
    private static String[] ignoreTypes;

    public void init(FilterConfig config) throws ServletException {
        defaultUrl = config.getInitParameter("defaultUrl");
        String ignoreTypes = config.getInitParameter("ignoreTypes");
        if (ignoreTypes != null && !ignoreTypes.trim().equals("")) {
            this.ignoreTypes = ignoreTypes.split(",");
        }
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws
            ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestUri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String url = requestUri.substring(contextPath.length());


        boolean isIgnoreType = false;
        if (ignoreTypes != null) {
            for (int i = 0; i < ignoreTypes.length; i++) {
                if (url.endsWith("." + ignoreTypes[i])) {
                    isIgnoreType = true;
                    break;
                }
            }
        } else {
            chain.doFilter(request, response);
        }

        if (url.indexOf("/login.jsp") > -1 || url.indexOf("/index.jsp") > -1
                || url.indexOf("/UserLoginServlet") > -1
                || url.indexOf("/UserRegisterServlet") > -1
                || url.equals("/")
                || isIgnoreType == true
        ) {
            System.out.println(url + "这是登录入口或者静态资源，放行");
            chain.doFilter(request, response);
        } else {
            //状态判断
            System.out.println("当前登录状态:" + request.getSession().getAttribute("isLogin"));
            if (request.getSession().getAttribute("isLogin") == null) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html");
                response.getWriter().write("No permission, please log in! 没有权限！");
                response.getWriter().write("<a href='login.jsp'>点我登录或注册</a>");
            } else if (request.getSession().getAttribute("isLogin").equals("true")) {
                chain.doFilter(request, response);
            }
        }
    }
}
